﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Excel;
namespace BYManageInfoSystem
{
    public partial class Frm_YearFeeShouldRecvNotRecv : Form
    {
        private DGBY.BLL.FeeShouldRecvNotRecvTab m_bllFeeShouldRecvNotRecvTab = new DGBY.BLL.FeeShouldRecvNotRecvTab();

        public Frm_YearFeeShouldRecvNotRecv()
        {
            InitializeComponent();
        }
        public class CustomMergedCellEvaluator : Infragistics.Win.UltraWinGrid.IMergedCellEvaluator
        {
            // 合并日期相同的单元格（无需时间精确相同）
            public bool ShouldCellsBeMerged(UltraGridRow row1, UltraGridRow row2, UltraGridColumn column)
            {
                string str1 = (string)row1.GetCellValue(column);
                string str2 = (string)row2.GetCellValue(column);

                return str1 == str2;

            }

        }
        public void LocalPrintPreveiw()
        {
            Infragistics.Shared.ResourceCustomizer rc = Infragistics.Win.Printing.Resources.Customizer;//Resources.Customizer;
            rc.SetCustomizedString("PrintPreview_DialogCaption", "打印预览");
            rc.SetCustomizedString("PrintPreview_Tool_Print", "打印(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_ClosePreview", "关闭(&C)");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuPreviewZoom", "显示比例");
            rc.SetCustomizedString("PrintPreview_Tool_Current_Page", "当前页");
            rc.SetCustomizedString("PrintPreview_Tool_Exit", "退出(&X)");
            rc.SetCustomizedString("PrintPreview_Tool_First_Page", "第一页");
            rc.SetCustomizedString("PrintPreview_Tool_Go_To", "跳至");
            rc.SetCustomizedString("PrintPreview_Tool_Last_Page", "最后一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_Page", "下一页");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_Page", "前一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_View", "下一视图(&N)");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_View", "前一视图(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_Hand_Tool", "手型工具(&H)");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Setup", "页面设置(&U)");
            rc.SetCustomizedString("PrintPreview_Tool_Snapshot_Tool", "快照工具(&S)");
            rc.SetCustomizedString("PrintPreview_Tool_View", "视图(&V)");
            rc.SetCustomizedString("PrintPreview_Tool_Whole_Page", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom", "缩放(&Z)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In", "放大");

            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out", "缩小");

            rc.SetCustomizedString("PrintPreview_ToolCategory_Context_Menus", "上下文菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_File", "文件");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Menus", "菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Tools", "工具栏");
            rc.SetCustomizedString("PrintPreview_ToolCategory_View", "视图");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Zoom_Mode", "缩放模式");

            rc.SetCustomizedString("PrintPreview_ToolTip_ClosePreview", "关闭");
            rc.SetCustomizedString("PrintPreview_ToolTip_Zoom", "缩放");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "页:{0}/{1}");

            rc.SetCustomizedString("CustomizeImg_ToolBar_MenuBar", "菜单");
            rc.SetCustomizedString("CustomizeImg_ToolBar_Standard", "标准");
            rc.SetCustomizedString("CustomizeImg_ToolBar_View", "视图");
            rc.SetCustomizedString("PrintPreview_Tool_File", "文件(&F)");
            rc.SetCustomizedString("PrintPreview_Tool_Tools", "工具(&T)");
            rc.SetCustomizedString("PrintPreview_Tool_Dynamic_Zoom_Tool", "动态缩放工具(&D)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out_Tool", "缩小工具");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In_Tool", "放大工具");
            // rc.SetCustomizedString("PrintPreview_Tool_Page_Layout","菜单");
            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PreviewRowColSelection_SelectedPages", "{0} x {1} 页");

            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Width", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_MarginWidth", "文字宽度");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_PageWidth", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_WholePage", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Layout", "页面布局");
            rc.SetCustomizedString("PrintPreview_Tool_Margin_Width", "文字宽度");
            rc.SetCustomizedString("ContextMenuPreviewHand", "缩放视图");


            rc.SetCustomizedString("PrintPreview_Tool_Reduce_Page_Thumbnails", "缩小");
            rc.SetCustomizedString("PrintPreview_Tool_Show_Page_Numbers", "显示页号");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuThumbnail", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Enlarge_Page_Thumbnails", "放大");
            rc.SetCustomizedString("PrintPreview_Tool_Thumbnails", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Continuous", "连续排序");
            //说明
            rc.SetCustomizedString("StatusBar_DynamicZoom_Instructions", "单击并拖动进行缩放操作");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "当前页: {0} / {1}");
            rc.SetCustomizedString("StatusBar_SnapShot_Instructions", "单击并拖动,系统将选定矩型区域复制到剪帖板");
            rc.SetCustomizedString("StatusBar_ZoomIn_Instructions", "单击并拖动,系统将放大选定矩型区域");
            rc.SetCustomizedString("StatusBar_ZoomOut_Instructions", "单击并拖动,系统将缩小选定矩型区域");
            rc.SetCustomizedString("StatusBar_Hand_Instructions", "单击并拖动以便显示更多内容");
        }
        private void MakeColumnTrue(DataTable dt)
        {
            dt.Columns.Add("序号", System.Type.GetType("System.Int32"));
            dt.Columns.Add("部门", System.Type.GetType("System.String"));
            dt.Columns.Add("客户", System.Type.GetType("System.String"));
            for (int i = 1; i < 13; i++)
            {
                dt.Columns.Add("应收未收费" + i.ToString(), System.Type.GetType("System.Decimal"));
                dt.Columns.Add("更改后应收未收费" + i.ToString(), System.Type.GetType("System.Decimal"));
            }
                
        }
        /// 取得某月的第一天
        /// </summary>
        /// <param name="datetime">要取得月份第一天的时间</param>
        /// <returns></returns>
        private DateTime FirstDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }
        /// <summary>
        /// 取得某月的最后一天
        /// </summary>
        /// <param name="datetime">要取得月份最后一天的时间</param>
        /// <returns></returns>
        private DateTime LastDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }
        private void ShowAllRecordInDataGridViewTrue()
        {
            ultraGrid1.DataSource = null;
            DateTime dtFirst1 = new DateTime(this.dateTimePickerDate.Value.Year, 1, 1);
            DateTime dtEnd1 = new DateTime(this.dateTimePickerDate.Value.Year, 12, 31);
            DataSet ds2 = m_bllFeeShouldRecvNotRecvTab.GetList(@"ShenBaoDate >= '" + dtFirst1.Date + "'"
                                     + " and ShenBaoDate <= '" + dtEnd1.Date + "'");

            Dictionary<string, string> dicFac2Dep = new Dictionary<string, string>();

            if (ds2.Tables.Count > 0 && ds2.Tables[0].Rows.Count > 0)
            {

                for (int i = 0; i < ds2.Tables[0].Rows.Count; i++)
                {
                    string strFac = ds2.Tables[0].Rows[i]["客户"].ToString();
                    string strDep = ds2.Tables[0].Rows[i]["部门"].ToString();
                    if (!dicFac2Dep.Keys.Contains(strFac))
                        dicFac2Dep.Add(strFac, strDep);
                }

            }

            DataTable dtNew = new DataTable();
            MakeColumnTrue(dtNew);

            int nSeq = 0;
            foreach(string strTemp in dicFac2Dep.Keys)
            {
                nSeq++;
                DataRow drTotal = dtNew.NewRow();
                drTotal["序号"] = nSeq.ToString();
                drTotal["部门"] = dicFac2Dep[strTemp];
                drTotal["客户"] = strTemp;
                for (int i = 1; i < 13; i++)
                {
                    drTotal["应收未收费" + i.ToString()] = 0;
                    drTotal["更改后应收未收费" + i.ToString()] = 0;
                }
                dtNew.Rows.Add(drTotal.ItemArray);
            }

            for (int i = 1; i < 13; i++)
            {
                DateTime dtMonth = new DateTime(this.dateTimePickerDate.Value.Year, i, 1);
                DateTime dtFirst = FirstDayOfMonth(dtMonth);
                DateTime dtEnd = LastDayOfMonth(dtMonth);
                DataSet ds = m_bllFeeShouldRecvNotRecvTab.GetList(@"ShenBaoDate >= '" + dtFirst.Date + "'"
                                         + " and ShenBaoDate <= '" + dtEnd.Date + "'");

                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {

                    for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                    {
                        string strFac = ds.Tables[0].Rows[j]["客户"].ToString();
                        Decimal dtTemp = Convert.ToDecimal(ds.Tables[0].Rows[j]["应收未收费"].ToString());
                        Decimal dtTempTrue = Convert.ToDecimal(ds.Tables[0].Rows[j]["更改后应收未收费"].ToString());
                        for (int k = 0; k < dtNew.Rows.Count; k++)
                        {
                            string strFacTemp = dtNew.Rows[k]["客户"].ToString();
                            if(strFacTemp.CompareTo(strFac) == 0)
                            {
                                dtNew.Rows[k]["应收未收费" + i.ToString()] = dtTemp;
                                dtNew.Rows[k]["更改后应收未收费" + i.ToString()] = dtTempTrue;
                                break;
                            }
                        }
                    }

                }
            }


            ultraGrid1.DataSource = dtNew;
            ProcessMultiHeader();

        }
        private void ProcessMultiHeader()
        {
            int nSpanX = 0;
            int nOriginX = 0;
            int nOriginXTemp = 0;
            bool bSpan = false;
            UltraGridColumn ultraGridColumn1 = null;

            foreach (UltraGridColumn column2 in this.ultraGrid1.DisplayLayout.Bands[0].Columns)
            {
                string str = column2.Header.Caption;
                //if (str == "总金额")
                //    bSpan = false;

                if (!bSpan)
                {
                    //if (str == "1-3季度" || str == "10月份" || str == "11月份"
                    //    || str == "12月份" || str == "第四季度合计" || str == "本年累计")
                    //    continue;
                    column2.RowLayoutColumnInfo.SpanY = 4;
                    if (column2.Hidden == false)
                        nOriginXTemp += 2;
                }
                else
                {
                    nSpanX += 2;
                    column2.RowLayoutColumnInfo.OriginY = 2;
                }
                if (str == "客户")
                {
                    bSpan = true;
                    nOriginX = nOriginXTemp;
                }
            }

            for (int i = 1; i < 13; i++)
            {
                ultraGridColumn1 = ultraGrid1.DisplayLayout.Bands[0].Columns.Add(i.ToString() + "月", i.ToString() + "月");
                ultraGridColumn1.CellActivation = Activation.Disabled;
                ultraGridColumn1.SortIndicator = SortIndicator.Disabled;
                ultraGridColumn1.RowLayoutColumnInfo.PreferredCellSize = new Size(1, 1);
                ultraGridColumn1.RowLayoutColumnInfo.AllowLabelSizing = RowLayoutSizing.None;
                ultraGridColumn1.RowLayoutColumnInfo.LabelPosition = LabelPosition.LabelOnly;
                ultraGridColumn1.RowLayoutColumnInfo.OriginX = nOriginX + (i -1) * 4;//有2个列隐藏了
                ultraGridColumn1.RowLayoutColumnInfo.OriginY = 0;
                ultraGridColumn1.RowLayoutColumnInfo.SpanX = 4;
                ultraGridColumn1.RowLayoutColumnInfo.SpanY = 2;
            }


        }
        private void Frm_YearFeeShouldRecvNotRecv_Load(object sender, EventArgs e)
        {

        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            ShowAllRecordInDataGridViewTrue();
        }

        private void buttonExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            this.ultraGridPrintDocument1.Grid = this.ultraGrid1;
            this.ultraPrintPreviewDialog1.Document = this.ultraGridPrintDocument1;
            this.ultraPrintPreviewDialog1.ShowDialog(this);
        }

        private void ultraGrid1_InitializeRow(object sender, InitializeRowEventArgs e)
        {
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextVAlign = VAlign.Middle;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextVAlign = VAlign.Middle;

            ultraGrid1.DisplayLayout.Bands[0].Columns["部门"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["部门"].MergedCellEvaluator = new
   CustomMergedCellEvaluator();
        }

        private void ultraGridExcelExporter1_CellExported(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.CellExportedEventArgs e)
        {
            // Get the cell being exporter
            UltraGridCell cell = e.GridRow.Cells[e.GridColumn];

            // Get the Merged cells. 
            UltraGridCell[] mergedCells = cell.GetMergedCells();


            // Check to see if there are any merged cells. If not, we don't need to do anything. 
            if (mergedCells != null)
            {
                // There are merged cells. Check to see if the cell being exported is the first one. 
                bool isFirstCell = true;
                foreach (UltraGridCell mergedCell in mergedCells)
                {
                    if (cell.Row.Index > mergedCell.Row.Index)
                    {
                        // If the cell being exported has a higher index that any of the cells
                        // it is merged with, them it's not the first cell and we should already
                        // have handled the merge. 
                        isFirstCell = false;
                        break;
                    }
                }

                // If it is the first cell, merge this cell with the cells below it based on the 
                // count of the merged cells. 
                if (isFirstCell)
                {
                    int rowIndex = e.CurrentRowIndex;
                    int colIndex = e.CurrentColumnIndex;
                    Infragistics.Excel.WorksheetMergedCellsRegion mergedRegion = e.CurrentWorksheet.MergedCellsRegions.Add(
                        rowIndex,
                        colIndex,
                        rowIndex + (mergedCells.Length - 1),
                        colIndex);
                    mergedRegion.CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Center;
                    mergedRegion.CellFormat.VerticalAlignment = Infragistics.Excel.VerticalCellAlignment.Center;
                }

            }
        }

        private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            ultraGrid1.DisplayLayout.Bands[0].UseRowLayout = true;
            ultraGrid1.DisplayLayout.Override.RowSizing = RowSizing.AutoFree;
        }
    }
}
